package cn.jinshengda.controller;


import cn.jinshengda.Dto.EmployeeDto;
import cn.jinshengda.entity.*;
import cn.jinshengda.service.*;
import cn.jinshengda.utils.DateUtil;
import cn.jinshengda.utils.GetAgeUtil;
import cn.jinshengda.utils.YearUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import org.springframework.stereotype.Controller;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author ${author}
 * @since 2022-01-08
 */
@RestController
@CrossOrigin
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;
    @Autowired
    private DegreeService degreeService;
    @Autowired
    private PositionService positionService;
    @Autowired
    private ResumeService resumeService;
    @Autowired
    private DailyPaperService dailyPaperService;
    @Autowired
    private MonthlyPaperService monthlyPaperService;
    @Autowired
    private DepartmentService departmentService;


    @GetMapping("employee/queryByPage")
    public Map<String,Object> queryAll(@RequestParam(value = "page",defaultValue = "1") Integer pageNow,
                                   @RequestParam(value = "per_page",defaultValue = "3")Integer rows){
        Page<Employee> employeePage = new Page<>(pageNow, rows);
        int sizeCount = employeeService.count(null);
        Map<String,Object> map=new HashMap<>();
        employeeService.page(employeePage, null);
        List<Employee> list = employeePage.getRecords();
//        List<Employee> list = employeeService.list(null);
        for (Employee employee : list) {
            //根据岗位查
            int age = DateUtil.getAge(employee.getBirthday());
            employee.setAge(age);
            String constellation = DateUtil.getConstellation(employee.getBirthday());
            employee.setConstellation(constellation);

            Position position = positionService.getById(employee.getPositionId());
            employee.setPositionName(position.getName());
            //根据学历查
            Degree degree = degreeService.getById(employee.getDegreeId());
            employee.setDegree(degree);
            //map.put("education",degree);

            QueryWrapper<Resume> queryWrapper=new QueryWrapper<>();
            queryWrapper.eq("employee_id",employee.getId());
            List<Resume> resumes = resumeService.list(queryWrapper);
            employee.setResume(resumes);
            //map.put("resume",resume);

            QueryWrapper<DailyPaper> queryWrapper1=new QueryWrapper<>();
            queryWrapper1.eq("employee_id", employee.getId());
            List<DailyPaper> dailyPapers = dailyPaperService.list(queryWrapper1);
            employee.setDailyPapers(dailyPapers);
            //map.put("dailyPapers",dailyPapers);

            QueryWrapper<MonthlyPaper> queryWrapper2=new QueryWrapper<>();
            queryWrapper2.eq("employee_id", employee.getId());
            List<MonthlyPaper> monthlyPapers = monthlyPaperService.list(queryWrapper2);
            employee.setMonthlyPapers(monthlyPapers);
            //map.put("monthlys",monthlyPapers);
            Department department = departmentService.getById(employee.getDepartmentId());
            employee.setDepartment(department);
        }
        map.put("page",pageNow);
        System.out.println(sizeCount);
        int pageNum=sizeCount%rows==0?sizeCount/rows:sizeCount/rows+1;
        map.put("pageNum",pageNum);
        map.put("data",list);
        return map;
    }


    @GetMapping("employee/queryByDepartment/{department_id}")
    public Map<String,Object> queryByDeptId(@PathVariable(value = "department_id",required = false) Integer department_id,
                                        @RequestParam(value = "page",defaultValue = "1") Integer pageNow,
                                        @RequestParam(value = "per_page",defaultValue = "3")Integer rows){
        IPage<Employee> iPage=new Page<>(pageNow,rows);
        QueryWrapper<Employee> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("department_id", department_id);
        iPage=employeeService.page(iPage,queryWrapper);
        List<Employee> list = iPage.getRecords();
        for (Employee employee : list) {
            String age = GetAgeUtil.evaluate(employee.getNumberId());
            employee.setAge(Integer.parseInt(age));

            Position position = positionService.getById(employee.getPositionId());
            employee.setPositionName(position.getName());

            Degree degree = degreeService.getById(employee.getDegreeId());
            employee.setDegree(degree);

            QueryWrapper<Resume> queryWrapper3=new QueryWrapper<>();
            queryWrapper3.eq("employee_id",employee.getId());
            List<Resume> resumes = resumeService.list(queryWrapper3);
            employee.setResume(resumes);

            QueryWrapper<DailyPaper> queryWrapper1=new QueryWrapper<>();
            queryWrapper1.eq("employee_id", employee.getId());
            List<DailyPaper> dailyPapers = dailyPaperService.list(queryWrapper1);
            employee.setDailyPapers(dailyPapers);

            QueryWrapper<MonthlyPaper> queryWrapper2=new QueryWrapper<>();
            queryWrapper2.eq("employee_id", employee.getId());
            List<MonthlyPaper> monthlyPapers = monthlyPaperService.list(queryWrapper2);
            employee.setMonthlyPapers(monthlyPapers);

            Department department = departmentService.getById(department_id);
            employee.setDepartment(department);
        }
        Map<String,Object> map=new HashMap<>();
        Integer sizeCount = employeeService.queryByDepartmentCount(department_id);
        map.put("page",pageNow);
        System.out.println(sizeCount);
        int pageNum=sizeCount%rows==0?sizeCount/rows:sizeCount/rows+1;
        map.put("pageNum",pageNum);
        map.put("data",list);
        return map;
    }


    @PostMapping("employee/add/{departmentId}/{resume}")
    public void saveEmp(@RequestBody cn.jinshengda.Dto.EmployeeDto employeeDto, @PathVariable("departmentId") Integer departmentId, @PathVariable("resume") Integer positionId){
        System.out.println(employeeDto.toString());
        System.out.println(departmentId+"--------"+positionId);
        employeeDto.setDepartmentId(departmentId);
        employeeDto.setPositionId(positionId);

        Employee employee = new Employee();
        BeanUtils.copyProperties(employeeDto, employee);

        String constellation = DateUtil.getConstellation(employeeDto.getBirthday());
        int age = DateUtil.getAge(employeeDto.getBirthday());

        employee.setConstellation(constellation);
        employee.setAge(age);
        Degree degree = new Degree();
        degree.setAdmissionTime(employeeDto.getAdmissionTime());
        degree.setGraduationTime(employeeDto.getGraduationTime());
        degree.setSchool(employeeDto.getSchool());
        degree.setEducation(employeeDto.getEducation());

        degreeService.save(degree);

        employee.setDegreeId(degree.getId());
        employeeService.save(employee);

        Resume resume = new Resume();
        resume.setStartDate(new Date());
        Position position = positionService.getById(positionId);
        resume.setJobName(position.getName());
        resume.setEmployeeId(employee.getId());
        resumeService.save(resume);
    }

    @GetMapping("employee/searchEducation")
    public ResponseEntity<Map<String,Object>> searchEducation(@RequestParam(value = "page",defaultValue = "1") Integer pageNow,
                                                              @RequestParam(value = "per_page",defaultValue = "3")Integer rows,
                                                              @RequestParam(value = "educationName",required = false) String education,
                                                              @RequestParam(value = "workYearsName",required = false) String workYearsName){
        System.out.println(pageNow+"---"+rows+"---"+education+"---"+workYearsName);
        Map<String, Object> map = employeeService.searchEducation(pageNow,rows,education,workYearsName);
        return new ResponseEntity<>(map,HttpStatus.OK);
    }


    /*
    修改员工岗位
     */
    @PatchMapping("employee/updatePosition")
    public void updatePosition(@RequestParam("employeeId") Integer id,@RequestParam("resumeId") Integer positionId){
        //根据员工查出要修改的员工
        Employee employee = employeeService.getById(id);

        /*
        根据员工id以及岗位名 找出对应履历  *注意*这里的岗位名必须根据员工的岗位id查出岗位信息之后获取岗位名
        接着把上一份履历的结束时间set进去
         */

        QueryWrapper<Resume> queryWrapper=new QueryWrapper<>();
        Position position = positionService.getById(employee.getPositionId());
        queryWrapper.eq("employee_id", employee.getId())
                    .eq("job_name", position.getName());
        Resume resume = resumeService.getOne(queryWrapper);
        resume.setEndDate(new Date());
        resumeService.updateById(resume);


        //*注意*这里的setPositionId必须放在查上一份履历之后  不然已经更新了新的岗位  在履历里是查不到上一份履历信息的
        //修改员工岗位
        employee.setPositionId(positionId);
        employeeService.updateById(employee);


        //修改员工岗位之后开始一段新的履历
        Resume resume1 = new Resume();
        resume1.setStartDate(new Date());
        resume1.setJobName(positionService.getById(employee.getPositionId()).getName());
        resume1.setEmployeeId(id);
        resumeService.save(resume1);

    }

    /*
     * @Author Lxy
     * @Description //TODO 员工离职 添加员工离职原因
     * @Param
     * @return
    */
    @DeleteMapping("employee/deleteEmployee/{employeeId}/{separation}")
    public ResponseEntity<Void> deleteEmployee(@PathVariable("employeeId") Integer employeeId,@PathVariable("separation") String separation){

        //System.out.println(employeeId+"------"+separation);
        Employee employee = new Employee();
        employee.setId(employeeId);
        employee.setSeparationReason(separation);
        //添加员工离职原因
        employeeService.updateById(employee);
        //逻辑删除该员工
        employeeService.removeById(employee);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    @GetMapping("employee/export")
    public void export(int page){
        employeeService.export(page);
    }

    @GetMapping("/employee/queryByMonthEmployeeAndCount")
    public ResponseEntity<Map<String,Object>> initEmployee(){
        Map<String, Object> map = employeeService.queryByMonthEmployee();
        return new ResponseEntity<>(map,HttpStatus.OK);
    }

    /*
     * @Author lxy
     * @Description //TODO 每月新员工注册情况
     * @Param startMonth 开始月份 endMonth 结束月份
     * @return 查询区间员工注册情况
     **/
    public ResponseEntity<Map<String,Object>> queryByMonthEmployeeCount(@RequestParam(value = "startMonth",required = false) Date startMonth,
                                                                        @RequestParam(value = "endMopnth",required = false)Date endMonth){

//        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
//        Date date = new Date();
//        String format = sdf.format(date);
        if (startMonth==null) startMonth=new Date();
        if (endMonth==null) endMonth=new Date();
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd");
        String startDate=simpleDateFormat.format(startMonth);
        String endDate = simpleDateFormat.format(endMonth);
        List<String> list = YearUtils.getYear(startDate, endDate);


        return new ResponseEntity<>(HttpStatus.OK);
    }

}

